# create-sqlite.pm
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

package CCNCore::create_sqlite;
use strict; use warnings;

use CCN::Database;
use CCNCore::Database::GUI;
use CCNCore::Provisioning::Local;
use CCNCore::Home;
use CCNCore::Scripting;

sub system_file($)
{
    my $pk = shift;
    return CCNCore::Home::config."/manager/system-${pk}.sqlite3";
}

sub run # ($p[,$server_pk])
{
    my $p = shift;
    my $target_pk = shift; # Optional: server.pk to generate for

    # Connect to the source database (normally in MySQL)
    our $db_from = new CCNCore::Database::GUI($p);

    $db_from->sql_begin();

    our $env = {};

    $env->{base_system_pk} = $db_from->sql_get(
        q(SELECT the_system FROM db_clusters WHERE pk = (SELECT db_cluster FROM provisioning))
        );
    warn('Cannot locate system ID for provisioning'), $db_from->sql_rollback(), return undef
        if not defined $env->{base_system_pk};

    my $version = time();

    my $sql = q(SELECT id FROM systems);
    $sql = "SELECT the_system FROM server WHERE id = $target_pk" if defined $target_pk;

    $db_from->sql_do_for($sql,
    sub
    {
        $env->{system_pk} = shift;

        # Create the SQLite export database
        my $system_file = CCNCore::Home::manager.'/lib/sql/system.sql';
        #  = Feed system.sql into sqlite3

        my $sqlite_file = system_file($env->{system_pk});

        use CCN::sql_copy;
        our $db_to = CCN::sql_copy::initialize_sqlite3($sqlite_file,$system_file);
        CCN::sql_copy::copy($db_from,$db_to,$system_file,$env,$version);
    });

    $db_from->sql_commit();

    if( not defined $target_pk                         # Generic case: all systems were generated
        or $env->{system_pk} == $env->{base_system_pk} # Server-specific: make sure the system we generated is our local one
    )
    {
        # Copy the file we just built to the local location.
        my $target = $CCNCore::Provisioning::Local::_name;
        my $base_sqlite_file = system_file($env->{base_system_pk});
        unlink $target;
        CCN::Scripting::exec_command("cp '$base_sqlite_file' '$target'");
    }

    return $version;
}
1;